
package io.gitee.chearnee.fw.socket.component.channelHandler;

import io.gitee.chearnee.fw.socket.component.NettyDispatcher;
import io.gitee.chearnee.fw.socket.entity.MsgEntity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class DispatcherChannelHandler extends SimpleChannelInboundHandler<MsgEntity> {

    private final NettyDispatcher tcpDispatcher = NettyDispatcher.getInstance();

    private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(
            Unpooled.copiedBuffer("HEARTBEAT", CharsetUtil.UTF_8));

    protected void messageReceived(ChannelHandlerContext channelHandlerContext, MsgEntity msgEntity) throws Exception {
        tcpDispatcher.msgReceived(channelHandlerContext,msgEntity);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("netty serve error",cause);
        ctx.close();
        super.exceptionCaught(ctx, cause);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MsgEntity msgEntity) {
        log.info("netty serve error",msgEntity);
        tcpDispatcher.msgReceived(channelHandlerContext,msgEntity);
    }
}
